﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ZhangZhao.RenChangYou
{
    public partial class ChangeCity : System.Web.UI.Page
    {
        protected string UserCity
        {
            get
            {
                return Request.QueryString["city"];
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string city = this.UserCity;

            if (string.IsNullOrWhiteSpace(city))
            {
                city = GetCityCookie();

                if (string.IsNullOrWhiteSpace(city))
                {
                    city = GetCityFromIP();
                }
            }

            SaveCityCookie(city);

            GetCityProducts(city);
        }

        private string GetCityFromIP()
        {
            return "沈阳";
        }

        private void SaveCityCookie(string city)
        {
            HttpCookie cookie = new HttpCookie("UserCity");
            cookie.Values["city"] = city;
            cookie.Values["country"] = "China";
            cookie.Expires = System.DateTime.Now.AddMonths(1);//设置过期时间1个月
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        private string GetCityCookie()
        {
            if (HttpContext.Current.Request.Cookies["UserCity"] != null)
            {
                string city = HttpContext.Current.Request.Cookies["UserCity"]["city"].ToString();
                string country = HttpContext.Current.Request.Cookies["UserCity"]["country"].ToString();

                return city;
            }

            return string.Empty;
        }

        private void GetCityProducts(string city)
        {
            this.ltlCity.Text = city;
        }
    }
}